package javadoc.doclet;
import cn.hutool.core.util.ReflectUtil;
import com.sun.javadoc.*;
import javadoc.entry.FildEntry;
import javadoc.entry.MethodEntry;
import javadoc.vo.ModelClassDocVO;

import java.util.ArrayList;
import java.util.List;

/**
 * 获取某一个java文件代码中属性对应的注释
 *
 * @author guzt
 */
public class Doclet {


    private static RootDoc rootDoc;
    private String javaBeanFilePath;

    public static boolean start(RootDoc root) {
        rootDoc = root;
        return true;
    }

    public Doclet(String javaBeanFilePath) {
        this.javaBeanFilePath = javaBeanFilePath;
    }

    public ModelClassDocVO exec() {
        ModelClassDocVO modelClassDocVO = new ModelClassDocVO();
        com.sun.tools.javadoc.Main.execute(new String[]{"-doclet", Doclet.class.getName(), "-docletpath",
                Doclet.class.getResource("/").getPath(), "-encoding", "utf-8", javaBeanFilePath});
        ClassDoc[] classes = rootDoc.classes();

        if (classes == null || classes.length == 0) {
            System.err.println(javaBeanFilePath + " 无ClassDoc信息");
            return modelClassDocVO;
        }

        List<FildEntry> entrys = new ArrayList<>();
        ClassDoc classDoc = classes[0];
        // 获取类的名称
        modelClassDocVO.setModelClassName(classDoc.name());
        // 获取类的注释
        String classComment = ReflectUtil.getFieldValue(classDoc, "documentation").toString();
        String spitStr = "\n";
        for (String msg : classComment.split(spitStr)) {
            if (!msg.trim().startsWith("@") && msg.trim().length() > 0) {
                modelClassDocVO.setModelCommentText(msg);
                break;
            }
        }
        // 获取属性名称和注释
        FieldDoc[] fields = classDoc.fields(false);
        for (FieldDoc field : fields) {
            entrys.add(new FildEntry(field.name(), field.type().typeName(), field.commentText()));
        }

        modelClassDocVO.setFildEntryList(entrys);


        MethodDoc[] methods = classDoc.methods();
        List<MethodEntry> methodEntries = new ArrayList<>(methods.length);
        for (MethodDoc method : methods) {
            String name = method.name();
            Type type = method.returnType();
            String rawCommentText = method.getRawCommentText();
            Parameter[] parameters = method.parameters();
            System.out.println(name);

        }
        return modelClassDocVO;
    }

    // 测试一下
    public static void main(String[] args) {
        Doclet doclet = new Doclet(
                "G:\\workspace\\idea_demo_workspace\\hcfUtils\\src\\test\\java\\javadoc\\model\\MessageHistory.java");
        ModelClassDocVO modelClassDocVO = doclet.exec();
        System.out.println("类注释：" + modelClassDocVO.getModelCommentText());
        System.out.println("属性字段注释如下：");
        modelClassDocVO.getFildEntryList().forEach(System.out::println);
    }
}